# coding:utf-8
# https://bbs.huaweicloud.com/blogs/425822
import gettext


class Localize:
    instance = None

    def __new__(cls, *args, **kwargs):
        if not cls.instance:
            cls.instance = super(Localize, cls).__new__(cls, *args, **kwargs)
        return cls.instance

    def __init__(self, **kwargs):
        self.domain = None
        self.locale_path = None
        if kwargs:
            self.init(**kwargs)

    def init(self, domain=None, locale_path=None):
        self.domain = domain
        self.locale_path = locale_path

        gettext.bindtextdomain(self.domain, self.locale_path)

    def get_translator(self, language):
        return gettext.translation(self.domain, self.locale_path, fallback=True, languages=[language])


localize = Localize()


if __name__ == '__main__':
    localize.init(domain='messages', locale_path='locale')

    zh_t = gettext.translation(localize.domain, localize.locale_path, fallback=True, languages=['zh_CN'])
    en_t = gettext.translation(localize.domain, localize.locale_path, fallback=True, languages=['EN'])
    _zh = zh_t.gettext
    _ = en_t.gettext

    # 固定字符串翻译
    print(_('数据查询异常'))
    print(_('数据查询异常智慧'))  # 未匹配到翻译 使用原始字段
    print(_zh('数据查询异常'))

    # 动态字段翻译
    print(_('{name}字段不存在').format(**{"name": "age"}))
    print(_('{name}字段不存在').format(**{"name": "status"}))

    print('*' * 30)
    mapper = {'en': _, 'zh': _zh}  # 请求上下文 用户动态选择使用中英文打印
    print('数据查询异常')
    print(mapper['en']('数据查询异常'))
    print(mapper['zh']('数据查询异常'))
